package application.main;

import application.view.UserInterface;
import application.view.gui.GraphicalUserInterface;

import java.util.Set;
import java.util.HashSet;

/**
 * 
 * This class is the start of the application. It manages the application overall, that it startup and shutdown
 * 
 * @author Philip Rasmussen & Morten Therkildsen
 */
public class Application {

	private static Set<QuitHandler> quitHandlers = new HashSet<QuitHandler>();
	private static boolean quitInProgress = false;

	/**
	 * The method that starts the whole application.
	 * 
	 * @param args		The arguments sent to the application. None are accepted/used
	 */
	public static void main(String[] args){

		UserInterface Ui = new GraphicalUserInterface();

		Ui.initialize();
	}

	/**
	 * Registers (adds) a new quit handler to ask permission when quitting.
	 * 
	 * @param handler	The quit handler to register
	 * @return	true if the quitHandler successfully was registered, otherwise false
	 */
	public static boolean registerQuitHandler(QuitHandler handler){

		if(handler == null) throw new NullPointerException("handler was null.");

		if(quitInProgress) return false;
		
		quitHandlers.add(handler);
		
		return true;
	}

	/**
	 * Unregisters (removes) a previously registered quit handler.
	 * 
	 * @param handler	The quit handler to unregister
	 * @return	true if the quitHandler successfully was unregistered, otherwise false
	 */
	public static boolean unregisterQuitHandler(QuitHandler handler){

		if(quitInProgress) return false;
			
		quitHandlers.remove(handler);
		
		return true;
	}

	/**
	 * Attempt to quit the application.
	 * The process may be stopped by previously registered quit handlers.
	 * 
	 * While running quitHandlers cannot be added or removed, and quit cannot be called
	 * 
	 * @return	false if the quit was cancelled
	 */
	public static boolean quit(){

		if(quitInProgress) return false;
		
		quitInProgress = true;
		boolean quit = true;

		for(QuitHandler handler : quitHandlers){ 
			quit &= handler.requestQuit(); 

			if(!quit){ 
				break;
			}
		}

		if(quit) System.exit(1);

		quitInProgress = false;
		
		return false;
	}

	/**
	 * Returns the path to the resources used by the application
	 * 
	 * @return The path to the resource directory
	 */
	public static String getResourceDirectoryPath(){

		// Code recoded in last minute to make the jar file able to run!
		/*String applicationResourceName = Application.class.getName().replaceAll("[.]", "/")+".class";	

		String path = Application.class.getClassLoader().getResource(applicationResourceName).getPath().replaceAll("%20"," ");
		
		return path.replaceAll(applicationResourceName, "application/resources/");*/
		
		return "resources/";
	}

	private Application(){/* Application objects cannot be created */}
}
